package com.canvasgames.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;

public class ReadText {
	public static String readTextResource(Context context, int resourceId){
		return readTextResource(context, resourceId, "UTF-8");
	}
	public static String readTextResource(Context context, int resourceId, String encoding) {
		InputStream is = context.getResources(). openRawResource(resourceId);
		try {
			return new String(getStreamContentAsBytes(is), encoding);
		} catch (Exception e) {
		e.printStackTrace();
		}
		return null;
	}
	public static String getString(InputStream is) {
		try {
			return new String(getStreamContentAsBytes(is), "UTF-8");
		}  catch (Exception e) {
		e.printStackTrace();
		}
		return null;
	}
	static public byte[] getStreamContentAsBytes(InputStream is) throws Exception {
		BufferedInputStream buffer = new BufferedInputStream(is);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] data = new byte[is.available()];
		int available = -1;
		while((available = buffer.read(data)) > -1) {
			output.write(data, 0, available);
		}
		return output.toByteArray();
	}
	static public ArrayList<String> extractImagesLink(String htmlData){
		ArrayList<String> list = new ArrayList<String>();
		Pattern p = Pattern.compile("images/\\w+\\.png");
		Matcher m = p.matcher(htmlData);
		while (m.find()) {
		String r = m.group();
		list.add(r);
		}
		return list;
	}
	static public void dataToFile(byte[] data, String fileName) throws IOException {
		File f = new File(fileName);
        File parent = f.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        if (!f.exists()) {
			f.createNewFile();
		}			
		FileOutputStream outputStream = new FileOutputStream(f);
	    outputStream.write(data);
	    outputStream.flush();
	    outputStream.close();
	}
	static public void stringToFile(String string, String fileName) throws IOException {
		byte[] data = string.getBytes();
		dataToFile(data,fileName);
	}
}
